﻿

//Bug: TypeError: Cannot call method 'setMinValue' of undefined 
//Modificado para buscar elementos,contenidos en varios paneles
//Restrinción los id de los elementos no debe contener caracter _
Ext.onReady(function () {
    Ext.apply(Ext.form.VTypes, {
    daterange: function (val, field) {
        var preName = "";
        var date = field.parseDate(val);
        var indexName = field.id.lastIndexOf("_");
        if (indexName > 0) {
            preName = field.id.substring(0, indexName + 1);
        }
        if (field.startDateField && (!date || (!field.dateRangeMax || (date.getTime() !== field.dateRangeMax.getTime())))) {
            var start = Ext.getCmp(preName + field.startDateField);

            if (start) {
                start.setMaxValue(date);
                field.dateRangeMax = date;
                start.validate();
            }
        } else if (field.endDateField && (!date || (!field.dateRangeMin || (date.getTime() !== field.dateRangeMin.getTime())))) {
            var end = Ext.getCmp(preName + field.endDateField);

            if (end) {
                end.setMinValue(date);
                field.dateRangeMin = date;
                end.validate();
            }
        }

        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
    });
   /*
    Ext.get(window.document).on('contextmenu', function (e) {
        e.preventDefault();
        return false;
    });
   */
    Ext.Window.prototype.forceHide = function (animateTarget) {
        this.hidden = true;
        if (animateTarget !== undefined)
            this.setAnimateTarget(animateTarget);

        if (!this.animateTarget) {
            this.el.hide();
            this.afterHide();
        }
        else
            this.animHide();
    };
  
});
/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var numericFormat =new Object();
numericFormat.toFixed=function (number, precision) {
    var multiplier = Math.pow(10, precision);
    return Math.round(number * multiplier) / multiplier;
};
// For convenience...
String.prototype.toFixed = function (number, precision) {
    return numericFormat.toFixed(number, precision);
};
String.prototype.capitalize = function () {
    return this.toLowerCase().replace(/(^|\s)([a-z])/g, function (m, p1, p2) { return p1 + p2.toUpperCase(); });
};
var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab",
        "Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"
    ],
    monthNames: [
		"Ene", "Feb", "Mar", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
        "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

//
var AppGlobalJs =
{
  
    _index: 0,
    showBug:function(msg)
    {
        try {
            console.log(msg);
        } catch (err) {
            Ext.Msg.alert('Aviso', msg);
        }
    },

    getIndex: function () {
        return this._index;
    },
    setIndex: function (index) {
        //if (index > -1 && index < App.GridPanel1.getStore().getCount()) {
        //    this._index = index;
        //}
    },
    //http://forums.asp.net/t/1696408.aspx
    querySt:function (ji) {
            hu = window.location.search.substring(1);
            gy = hu.split("&");
            for (i=0;i<gy.length;i++) {
                ft = gy[i].split("=");
                if (ft[0] == ji) {
                    return ft[1];
                }
            }
    },
    //Obtener valor de la propiedad de un objeto dado
    getValProp:function show_props(obj, objName) { 
        var result = ""; 
        for (var i in obj) {
            if (i.indexOf(objName) != -1) {
                result = obj[i];
                break;
            }
        } 
        return result; 
    },
    // Muestra el mensaje enviado como parametro con el icono de aviso
    showMsgError:function (msg) {
            Ext.Msg.show({
            title: 'Error',
            msg: msg,
        minWidth: 300,
        modal: true,
        icon: Ext.Msg.ERROR,
        buttons: Ext.Msg.OK
        });
    },
   // Muestra el mensaje enviado como parametro con el icono de aviso
   showMsgAviso: function (msg) {
        Ext.Msg.show({
            title: 'Aviso',
            msg: msg,
            minWidth: 300,
            modal: true,
            icon: Ext.Msg.INFO,
            buttons: Ext.Msg.OK
        });
    },
   showMsgFilter: function (tit,dataFiter) {
       var msg = '<p>Información filtrado por:</p><ol>';
  
       for (var i = 0; i < dataFiter.length;i++)
       {
           var rec   = dataFiter[i];
           var title = rec.field;
           msg += ' <li><b>' + title + '=</b> ';
           title = rec.data;
           msg += title.value + '</li> ';
       }
       msg += ' </ol>';
       if (dataFiter.length == 0) {
           Ext.Msg.show({
               title: tit,
               msg: 'Sin filtros',
               minWidth: 300,
               modal: true,
               icon: Ext.Msg.INFO,
               buttons: Ext.Msg.OK
           });
       }
       else {
           Ext.Msg.show({
               title: tit,
               msg: msg,
               minWidth: 300,
               modal: true,
               icon: Ext.Msg.INFO,
               buttons: Ext.Msg.OK
           });
       }
   },
   //Muestra el mensaje enviado como parametro con el icono de aviso
   showMsgAlerta:function(msg) {
       Ext.Msg.show({
           title: 'Aviso',
           msg: msg,
           minWidth: 300,
           modal: true,
           icon: Ext.Msg.WARNING,
           buttons: Ext.Msg.OK
       });
   },
    //Abrir vantana
   showWin: function (objwin, tit1, tit2, ticon) {
       try{
        if (typeof (tit1) != "undefined" & typeof (tit2) != "undefined")
            objwin.setTitle(Ext.String.format(" {0}: {1}", tit1, tit2));
        if (typeof (ticon) != "undefined")
            objwin.setIconCls("my-" + ticon);
        objwin.renderTo = Ext.getBody();
        objwin.show();
        return (objwin);
       } catch (jsbug) {
           this.showBug("AppGlobalJs.showWin: " + jsbug);
       }
    },
    //Cerrar ventana
    closeWin : function(objwin) {
        objwin.hide();
    },
    //Rango de Fechas
    onKeyUpDate: function (me) {
        try{
              
                var v = me.getValue();
                var field;
                if (me.startDateField) {
                    field = Ext.getCmp(me.startDateField);
                    field.setMaxValue(v);
                    me.dateRangeMax = v;
                } else if (me.endDateField) {
                    field = Ext.getCmp(me.endDateField);
                    field.setMinValue(v);
                    me.dateRangeMin = v;
                }
                field.validate();
        } catch (jsbug) {
            this.showBug("AppGlobalJs.onKeyUpDate: " + jsbug);
        }
    },
    obtenerPath: function() {
        return window.location.protocol + "//" + window.location.host;
    },
    //Mostrar visor pdf
   showPdf: function (pth, val) {
       var path     = this.obtenerPath();
       var _icon = "#PageWhiteCopy";
       var _fileExt = val.substring(val.lastIndexOf('.') + 1).toLowerCase();
       switch (_fileExt)
       {
           case "pdf":
               _icon = "#PageWhiteAcrobat";              
               break;
           case "docx":
           case "doc":
               _icon = "#PageWhiteWorld";
               break;
           default:
                _icon = "#PageWhiteCopy";
               break;
       }
    
       var w = new Ext.Window({
            closeAction: "destroy",
            renderTo: Ext.getBody(),
            iconCls: _icon,
            resizable: true,
            maximizable: false,
            minimizable: false,
            collapsible: false,
            draggable: true,
            isMinimized: false,
            isMaximized: false,
            minWidth: 500,
            minHeight: 450,
            width: 600,
            height: 480,
            isModal: false,
            constrain: true,
            loader: {
                url: path + "/pgDetailPdf.aspx?idx= " + val,
                //url: "http://localhost:9090/pgDetailPdf.aspx?idx= " + val,
                renderer: "frame",
                disableCaching: true,
                loadMask: {
                    showMask: true
                },
                listeners: {
                    load: function (control) {
                        control.target.iframe.dom.contentWindow.parentWindow = control.target;
                    }
                }
            },
            listeners: {
                close: {
                    fn: function (el) {
                        el.destroy();
                    }
                }
            }
        });

        w.show();
   },
   collapsePanel : function (pnl,me) {
     
       if(pnl.collapsed==false)
       {
           pnl.collapse();
       }
       else
       {
               
           pnl.expand();
       }
   },
   //Mostrar ventana url
   mostrarVentanaUrl: function (ruta, titulo, icon, id, closable) {
       var _iconCls = "#Pencil";
       var _id = "WinTestScreen";
       if (typeof (id) != "undefined")
           _id = id;
       if (typeof (icon) != "undefined" )
           _iconCls = icon;
       if ( icon == null)
           _iconCls = "";
       var windowConfig =
       {
            id:_id,
            //closeAction: "destroy",
            closeAction: "hide",
            renderTo: Ext.getBody(),
            iconCls: _iconCls,
            closable:true, 
            collapsible: false,
            isMinimized: false,
            isMaximized: true,
            title: titulo,
            width: 560,
            height: 560,
            isModal: false,
            constrain: true,
            loader: {
                url: ruta,
                renderer: "frame",
                disableCaching: true,
                loadMask: {
                    showMask: true
                },
                listeners: {
                    load: function (control) {
                        control.target.iframe.dom.contentWindow.parentWindow = control.target;
                    }
                }
            },
            listeners: {
                close: {
                    fn: function (el) {
                        el.destroy();
                    }
                }
            }
       };
       //Propiedad  <<closable>> por defecto true
       if (typeof (closable) != "undefined") {
           windowConfig.closable = closable;
       }
       var w = Ext.getCmp(windowConfig.id);
       if (!w)
       {
          w= new Ext.Window(windowConfig);

       } else
       {
          w.close();
          w= new Ext.Window(windowConfig);
       }
        w.show();
        w.maximize();
        return(w);
   },
   //Cerrar ventana url
   closeVentanaUrl: function (myWinUrl) {
       //try
       //{
             
       if (myWinUrl) {
           myWinUrl.close();
         }
                   //Ext.WindowMgr.each(function (w) {
                   //    var n = w.id.indexOf(_id);
                   //    if (n != -1) {
                   //        w.close()
                   //    }
                   //});

               
        //} catch (jsbug) {
        //   this.showBug("AppGlobalJs.closeVentanaUrl: " + jsbug);
        //}
   },
   GetListErrors: function (me) {
       try {
           var fields, errors;
           fields = me.getForm().getFields();
           errors = [];
           fields.each(function (field) {
               var listError = field.getErrors();
               if (listError.length == 0)
                   listError = field.getActiveErrors();

               Ext.Array.forEach(listError, function (error) {
                   errors.push({ name: field.getFieldLabel() || field.getName(), error: error });
               });
           });
           return (errors);
       } catch (jsbug) {
           this.showBug("AppGlobalJs.GetListErrors: " + jsbug)
       }
   },
   setReadOnly : function(frmGeneral,readOnly)
   {
       try{
           var fields = frmGeneral.getForm().getFields();
           fields.each(function (field) {
               if (field.rendered) {
                   field.el.dom.setAttribute("readOnly",readOnly);
               }
               field.setReadOnly(readOnly);
           });
       }catch(jsbug){
           AppGlobalJs.showBug("AppGlobalJs.SetReadOnly: " + jsbug)
       }
   },
   controlSesion : function () {
       Ext.Msg.show({
           title: 'Aviso',
           msg:'Su sesión ha expirado',
           buttons: Ext.Msg.OK,
           animEl: 'elId',
           icon: Ext.MessageBox.INFO
       });
       var loginUrl = this.obtenerPath();
       loginUrl = loginUrl + "/pgLogin.aspx";
       top.location.href = loginUrl;
       
   },
   redirectPage: function (url) {
        var redirectUrl = this.obtenerPath();
        redirectUrl = redirectUrl + "/" + url;
        top.location.href = redirectUrl;
    }

};

var AppLabelGlobalJs =
{   
    loaddoc_num_doc_01: "Número documentos obligatorio requerido no válido.Existen documentos pendientes de registrar hacer clic en icono <b>agregar documento.</b>",
    loaddoc_num_doc_02: "Número documentos obligatorio requerido no válido,falta subir <b>nueva versiones</b>",
    loaddoc_num_doc_03: "Formato Incorrecto",
    corrDoc_01: "Se requiere que agregue al menos 1 documento",
    pg_format_doc: "Formato Incorrecto. Formato valido doc",
    pg_datos_obli: "<b>Datos invalidos</b><br> Por favor ingrese los siguientes datos obligatorios:",
    pg_datos_valid: "<b>Datos invalidos</b><br> Por favor ingrese los siguientes datos:",
    pg_cer_invalid: "<b>Datos invalidos</b> Por favor ingrese nuevamente certificado<b>(.p12)</b>.",
    pg_dir_activo: "<b>ATENCIÓN</b> Al selecionar la opción activar usuario-director, los demás usuarios-directores seran desactivados"
};

